<?php
/**
 * Plugin Mobile Site.
 *
 * @package WP cr mobile
 */
class CRMobile_MobileSite
{
    public function __construct()
    {
        add_action('template_redirect', array($this, 'redirect'), 1);
    }

    public function redirect()
    {
        $url = parse_url($_SERVER['REQUEST_URI']);
        // not a CMob page; don't do anything and return
        if (stripos($url['path'], '/reviews/') === false) {
            return;
        }

        $url = explode('/', $url['path']);
        $search = array_search('reviews', $url);
        $review = $url[$search + 1];

        if (!in_array($review, $this->getCompanySlugs())) {
            return;
        }

        $companyID = array_search($review, $this->getCompanySlugs());
        $company = $this->getCompany($companyID);

        $slug = $this->slugify($company->name);
        if (isset($_POST['submit']) &&
            isset($_POST[$slug.'_mobile_review_nonce']) &&
            wp_verify_nonce($_POST[$slug.'_mobile_review_nonce'], $slug.'_mobile_review')
        ) {
            $rating = isset($_POST['rating']) ? $_POST['rating'] : 0;
            $this->saveForm($rating);
            echo CRMobile_Theme::getThanks($company, $rating, esc_attr($_POST['review']));
        } else {
            echo CRMobile_Theme::getForm($company);
        }
        die();
    }

    private function getCompany($id)
    {
        global $wpdb;
        $company_table = $wpdb->prefix . "cr_mobile_companies";
        $query = "SELECT * FROM $company_table WHERE ID = $id";
        $company = $wpdb->get_row($query, OBJECT);

        return $company;
    }

    private function getCompanySlugs()
    {
        // Get list of companies
        global $wpdb;
        $company_table = $wpdb->prefix . "cr_mobile_companies";
        $query = "SELECT id, name FROM $company_table";
        $companies = $wpdb->get_results($query, ARRAY_A);

        foreach ($companies as $company) {
            $slugs[$company['id']] = $this->slugify($company['name']);
        }
        return $slugs;
    }

    public static function slugify($text)
    {
        $text = stripslashes($text);
        $text = str_replace("&#039;", "", $text);
        $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
        $text = trim($text, '-');
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        $text = strtolower($text);
        $text = preg_replace('~[^-\w]+~', '', $text);
        if (empty($text)) {
            return 'n-a';
        }
        return $text;
    }

    private function saveForm($rating)
    {
        global $wpdb;
        $reviewTable = $wpdb->prefix . "cr_mobile_reviews";
        $company_table = $wpdb->prefix . "cr_mobile_companies";

        // Get company review threshold
        $id = $_POST['ID'];
        $query = "SELECT * FROM $company_table WHERE ID = $id";
        $company = $wpdb->get_row($query, OBJECT, 0);

        // Set status
        if ($rating <= $company->threshold) {
            $status = 'unpublished';
        } else {
            $status = 'published';
        }

        $mail = isset($_POST['email']) ? esc_attr($_POST['email']) : '';
        $name = isset($_POST['name']) ? esc_attr($_POST['name']) : '';

        $reviewTable = $wpdb->prefix . "cr_mobile_reviews";
        $rows_affected = $wpdb->insert(
            $reviewTable,
            array(
                'company_id'     => $_POST['ID'],
                'reviewer_name'  => $name,
                'reviewer_email' => $mail,
                'review_date'    => date("Y-m-d H:i:s"),
                'rating'         => $rating,
                'review'         => isset($_POST['review']) ? esc_attr($_POST['review']) : '',
                'status'         => $status
            )
        );

        // Email notifications
        CRMobile_Notification::notify($company, $_POST);
        CRMobile_Notification::mailReviewer($company, $rating, $mail);
        CRMobile_Notification::mailResponder($company, $mail);
        if ($company->sms) {
            $this->smsOptIn($company, $_POST['mobile']);
        }
    }

    private function smsOptIn($company, $mobile)
    {
        $args = array(
            'body' => "mN={$mobile}"
                      ."&sc={$company->sms_keyword}"
                      .'&me=MobileWebPage'
                      .'&ev=send'
                      .'&ac=0',
            'timeout' => '10000'        // 10 seconds
        );

        $resp = wp_remote_post('http://login2mobi.com/fbAPI', $args);
    }
}
